package com.sevlet;

import com.dao.UserDAO;
import com.impl.UserDAOImpl;
import com.model.UserDO;
import com.utils.*;
import com.vo.UserVO;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns={"/user.do"}) //Servlet映射到URL路径/user/register。
public class UserServlet extends HttpServlet {

    // 创建UserDAO实例
    public static final UserDAO userDAOImpl = new UserDAOImpl(); //声明了一个名为userDAOImpl的静态常量

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String action = request.getParameter("action");
        String servletPath = request.getServletPath();//获取客户端传来的URL字符串
        if ("register".equals(action)) {//对比字符串
            // 处理用户注册请求
            doRegister(request, response);
        } else if ("login".equals(action)) {
            //登录
            doLogin(request, response);
        } else if ("changePassword".equals(action)) {
            //修改用户密码
            doChangePassword(request, response);
        } else if ("sendCode".equals(action)) {
            sendCode(request, response);
        } else {
            // 跳转到登录页
            response.sendRedirect(request.getContextPath() + "/login.jsp");
        }

    }

    /**
     * 处理用户注册请求
     */
    private void doRegister(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String phone = request.getParameter("phone");
        String pwd = request.getParameter("password");
        String code = request.getParameter("code");
        // 从 Session 中获取验证码和时间戳
        String storedCodeAndTimestamp = (String) request.getSession().getAttribute(phone + ":code");
        if (storedCodeAndTimestamp == null) {
            out.print(R.fail("验证码未发送或已过期"));
            return;
        }
        String[] parts = storedCodeAndTimestamp.split("_");
        String storedCode = parts[0];
        String storedTimestamp = parts[1];

        // 检查验证码是否过期
        long currentTime = System.currentTimeMillis();
        long storedTime = Long.parseLong(storedTimestamp);
        if (currentTime - storedTime > 5 * 60 * 1000) {
            out.print(R.fail("验证码已过期"));
            return;
        }
        // 检查验证码是否正确
        if (!code.equals(storedCode)) {
            out.print(R.fail("验证码错误"));
            return;
        }
        try {
            userDAOImpl.register(phone, pwd);
            out.print(R.ok());
        } catch (BizException e) {
            out.print(R.fail(e.getMessage()));
        }
    }


    /**
     * 修改用户密码
     */

    private void doChangePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String phone = request.getParameter("phone");
        String newPassword = request.getParameter("newPassword");
        String code = request.getParameter("code");
        try {
            String originCode = request.getSession().getAttribute("code").toString();
            if (!code.equals(originCode)) {
                throw new BizException("验证码错误");
            }
            userDAOImpl.updatePassword(phone, newPassword, code);
            response.sendRedirect(request.getContextPath() + "/login.jsp?success=true");
        } catch (BizException e) {
            request.setAttribute("error", e.getMessage());
            request.getRequestDispatcher("/changePassword.jsp").forward(request, response);
        }
    }

    /**
     * 发送短信验证码
     */
    private void sendCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String phone = request.getParameter("phone");
        if (phone == null || phone.isEmpty()) {
            out.print(R.fail("手机号不能为空"));
            return;
        }

        String code = CommonUtil.getRandomCode(6);
        String res = SmsUtil.sendCode(phone, code);
        if (!"0".equals(res)) {
            out.print(R.fail("验证码发送失败"));
        }
        // 将验证码存入 Session
        HttpSession session = request.getSession();
        session.setAttribute(phone + ":code", code + "_" +System.currentTimeMillis());
        session.setAttribute("phone", phone);
        out.print(R.ok());
    }

    /**
     * 登录
     */
    private void doLogin(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        UserDO userDO = new UserDO();
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");
        userDO.setPhone(phone);
        userDO.setPassword(password);

        try {
            UserVO userVO = userDAOImpl.login(phone, password);
            request.getSession().setAttribute("user", userVO);
            out.print(R.ok());
        } catch (BizException e) {
            out.print(R.fail(e.getMessage()));
        }
    }

}